package com.cly.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.common.entity.result.Result;
import com.cly.common.entity.user.po.Address;
import com.cly.common.exception.CommonException;
import com.cly.common.util.ThreadLocalUtil;
import com.cly.user.mapper.AddressMapper;
import com.cly.user.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    /**
     * 添加地址
     * @param adress
     * @return
     */
    @Override
    public Result addAdress(Address address) {
        address.setUserId(ThreadLocalUtil.get());
        try {
            this.save(address);
            return Result.success();
        } catch (Exception e) {
            throw new CommonException("保持地址失败",e);
        }
    }

    /**
     * 获取地址
     * @return
     */
    @Override
    public Result<List<Address>> getAddressAll() {
        try {
            LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Address::getUserId,ThreadLocalUtil.get());
            List<Address> adressList = this.list(queryWrapper);
            return Result.success(adressList);
        } catch (Exception e) {
            throw new CommonException("获取地址事变", e);
        }
    }

    /**
     * 修改地址
     * @param adress
     * @return
     */
    @Override
    public Result updateAddress(Address adress) {
        try {
            if(this.getById(adress.getId()) == null){
                throw new CommonException("地址不存在");
            }
            adress.setUserId(ThreadLocalUtil.get());
            this.updateById(adress);
            return Result.success();
        } catch (Exception e) {
            throw new CommonException("修改地址失败",e);
        }
    }
}
